package com.example.blog.util;


import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

public class TencentUploadUtil {

    public static String bucketName = "rjlmpic-1300589041";
    public static String baseUrl= "https://rjlmpic-1300589041.cos.ap-nanjing.myqcloud.com/";

    //获取客户端
    public static COSClient  getCosClient(){
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials("AKIDb0A1h6v5fy2oKicMaXMxHMJM8fwvs9OO","y6zbHgneZDbiX1EAqFO6YiiTx94j7D3j");
        // 2 设置 bucket 区域
        ClientConfig clientConfig = new ClientConfig(new Region("ap-nanjing"));
        // 3 生成 cos 客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        return cosclient;
    }

    //上传
    public static String uploadFile(String path, File file) {
        COSClient cosclient  = getCosClient();
        // 上传 object, 建议 20M 以下的文件使用该接口
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path, file);
        // 设置 x-cos-security-token header 字段
        ObjectMetadata objectMetadata = new ObjectMetadata();
//        objectMetadata.setSecurityToken(sessionToken);
        putObjectRequest.setMetadata(objectMetadata);
        String rtValue = null;
        try {
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            rtValue = baseUrl + path;
        } catch (CosServiceException e) {
            //失败，抛出 CosServiceException
            e.printStackTrace();
        } catch (CosClientException e) {
            //失败，抛出 CosClientException
            e.printStackTrace();
        } finally {
            // 关闭客户端
            cosclient.shutdown();
            //返回文件的网络访问url
            return rtValue;
        }
    }

    //下载 传入文件的路径
    public static ResponseEntity<Object> download(HttpServletResponse response, String path) throws IOException {
        COSClient cosclient = getCosClient();
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, path);
        //System.out.println(getObjectRequest.getKey());
        // 限流使用的单位是 bit/s, 这里设置下载带宽限制为10MB/s
        //getObjectRequest.setTrafficLimit(80*1024*1024);
        COSObject cosObject = cosclient.getObject(getObjectRequest);
        //System.out.println(cosObject.toString());
        COSObjectInputStream cosObjectInput = cosObject.getObjectContent();


        InputStreamResource resource = null;
        try {
            resource = new InputStreamResource(cosObjectInput);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        ResponseFile responseFile = new ResponseFile();
//        responseFile.setResource(resource);
//        responseFile.setFileName(path);
        System.out.println((path.split("/")[1]));
        HttpHeaders headers = new HttpHeaders();
        //要暴露的属性，暴露了js可以拿到 https://blog.csdn.net/pgguoqi/article/details/106824957
        headers.add("Access-Control-Expose-Headers", "Content-Disposition");
        //headers.add("Content-Disposition", String.format("attachment;filename=%s", new String((path.split("/")[path.split("/").length-1]).getBytes("gbk"), "iso-8859-1")));
        headers.add("Content-Disposition", String.format("%s", URLEncoder.encode(path.split("/")[path.split("/").length-1], "UTF-8")));

        headers.add("Cache-Control", "no-cache,no-store,must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        ResponseEntity<Object> responseEntity = ResponseEntity.ok()
                .headers(headers)
//                .contentLength(cosObjectInput.get)
                .contentType(MediaType.parseMediaType("application/octet-stream"))

                .body(resource);
        cosclient.shutdown();
        return responseEntity;

//        response.reset();
//        response.setContentType("application/x-msdownload;charset=utf-8");
//        try {
//            response.setHeader("Content-Disposition", "attachment;filename="+new String((path.split("/")[1]).getBytes("gbk"), "iso-8859-1"));//下载文件的名称
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        ServletOutputStream sout = response.getOutputStream();
//        BufferedInputStream bis = null;
//        BufferedOutputStream bos = null;
//        try {
//            bis = new BufferedInputStream(cosObjectInput);
//            bos = new BufferedOutputStream(sout);
//            byte[] buff = new byte[2048];
//            int bytesRead;
//            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
//                bos.write(buff, 0, bytesRead);
//            }
//            bos.flush();
//            bos.close();
//            bis.close();
//        } catch (final IOException e) {
//            throw e;
//        } finally {
//            if (bis != null){
//                bis.close();
//            }
//            if (bos != null){
//                bos.close();
//            }
//        }
        // 关闭输入流
       // cosObjectInput.close();
       // cosclient.shutdown();

    }
}
